<template>
	<div class="uiue-card" style="margin-top: 0;" v-if="datas">
		<div class="tit">基本信息</div>
		<a-descriptions class="descri">
			<a-descriptions-item label="应用名称">{{ datas.appName }}</a-descriptions-item>
			<a-descriptions-item label="应用分类">{{
		$TOOL.dictTypeData('APP_CLASS', datas.appCategory)
	}}</a-descriptions-item>
			<a-descriptions-item label="应用范围">{{ $TOOL.dictTypeData('app_range', datas.appRange)
				}}</a-descriptions-item>
			<a-descriptions-item label="应用ID">{{ datas.appCode }}</a-descriptions-item>
			<!-- <a-descriptions-item label="应用关键字">{{ datas.appKeywords }}</a-descriptions-item> -->
			<!-- <a-descriptions-item label="应用状态">{{ datas.appStatus == 1 ? '有效' : '无效' }}</a-descriptions-item> -->
			<a-descriptions-item label="项目经理">{{ appContact }}</a-descriptions-item>
			<a-descriptions-item label="技术支持">{{ datas.versionNumber }}</a-descriptions-item>
			<a-descriptions-item label="应用三级系统名">{{ datas?.threeSystemName || '' }}</a-descriptions-item>
			<a-descriptions-item label="反馈接收人">{{ datas.operationsSupport }}</a-descriptions-item>
			<a-descriptions-item label="需求单编号">{{ datas.reqFormCode }}</a-descriptions-item>
			<!-- <a-descriptions-item label="用户范围">{{ datas.appAccountid }}</a-descriptions-item> -->
			<a-descriptions-item label="应用有效期">{{ datas.validTime }}</a-descriptions-item>
			<a-descriptions-item label="应用介绍" :contentStyle="contentStyle" class="scro">{{ datas.appDescription
				}}</a-descriptions-item>
			<a-descriptions-item label="其他说明" :contentStyle="contentStyle" class="scro">
				{{ datas.otherInfo }}
			</a-descriptions-item>
			<a-descriptions-item label="双端接入">{{ appAccess }}</a-descriptions-item>
			<a-descriptions-item label="应用归属">{{ platform }}</a-descriptions-item>
			<a-descriptions-item v-if="datas.appOnlineTime" label="移动端预计上线时间">{{ datas.appOnlineTime
				}}</a-descriptions-item>
		</a-descriptions>
		<a-descriptions>
			<a-descriptions-item label="是否接门户端待办">{{ filterRadio(datas.isPcTodo)
				}}</a-descriptions-item>
			<a-descriptions-item label="是否接门户端待阅">{{ filterRadio(datas.isPcReadtodo)
				}}</a-descriptions-item>
			<a-descriptions-item label="无法双端同步接入待办待阅原因" v-if="datas.noAccessTypeRemark">{{
		$TOOL.dictTypeData('REASON_ACCESS', datas.noAccessTypeRemark)
	}}</a-descriptions-item>
		</a-descriptions>
		<a-descriptions>
			<a-descriptions-item label="是否接移动端待办">{{ filterRadio(datas.isAppTodo)
				}}</a-descriptions-item>
			<a-descriptions-item label="是否接移动端待阅">{{ filterRadio(datas.isAppReadtodo)
				}}</a-descriptions-item>
			<a-descriptions-item label="无法双端同步接入待办待阅其他原因" v-if="datas.noAccessTypeRemark == 5">{{
		datas.appRemark
	}}</a-descriptions-item>
		</a-descriptions>
	</div>
	<div class="uiue-card" style="padding-top: 0" v-if="datas">
		<a-tabs v-model:activeKey="configKey">

			<a-tab-pane key="1" tab="移动端Html" force-render>
				<div class="tit">配置信息</div>
				<a-form ref="mobile" :model="formData" :rules="formRules" layout="vertical" class="form-box">
					<a-row :gutter="75">
						<a-col :span="8">

							<a-form-item name="appSource">
								<LabelDes label="应用来源" prop="appSource" />
								<a-select v-model:value="formData.appSource" placeholder="请选择应用来源"
									:options="tool.dictList('APP_SOURCE')" disabled allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item name="appVersion">
								<LabelDes label="版本号" prop="appVersion" />
								<a-input v-model:value="formData.appVersion" placeholder="请输入版本号" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item name="appVersionNote">
								<LabelDes label="版本说明" prop="appVersionNote" />
								<a-input v-model:value="formData.appVersionNote" placeholder="请输入版本说明" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="75">
						<a-col :span="8">
							<a-form-item name="appUrl">
								<LabelDes label="应用访问URL地址" prop="appUrlapp" />
								<a-input v-model:value="formData.appUrl" placeholder="请输入应用访问URL地址" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item name="isHideLogo">
								<LabelDes label="是否展示图标" prop="isHideLogoapp" />
								<a-radio-group v-model:value="formData.isHideLogo" :options="radioOption"
									name="isHideLogo" />
							</a-form-item>
						</a-col>
						<!-- <a-col :span="8">
							<a-form-item label="移动端上线时间" name="appOnlineTime">
								<a-date-picker ref="pickss" style="width: 100%" valueFormat="YYYY-MM-DD"
									:showToday="false" v-model:value="formData.appOnlineTime">
								</a-date-picker>
							</a-form-item>
						</a-col> -->
					</a-row>
					<a-row :gutter="75">
						<a-col :span="8" v-if="showPermis">
							<a-form-item label="名单权限" name="permission">
								<a-radio-group v-model:value="formData.permission" :options="radioOption11" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item name="param">
								<LabelDes label="参数信息" prop="param" />
								<a-textarea v-model:value="formData.param" disabled placeholder="参数信息自动生成" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item name="appLogo">
								<LabelDes label="logo" prop="appLogo" />
								<div class="upload-box">
									<a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card"
										class="avatar-uploader" :customRequest="customRequest" :accept="fileImgType"
										:before-upload="beforeUpload" @change="handleChange" @preview="handlePreview">
										<div v-if="fileList?.length == 0">
											<plus-outlined></plus-outlined>
											<div class="ant-upload-text">上传图片</div>
										</div>
									</a-upload>
									<div class="annotation">
										<div class="tit1">*注</div>
										<div>1.应用logo需要满足UI/UE规范;</div>
										<div>2.需要上传.png/.jpg/.jpeg格式文件;</div>
										<div>3.文件大小为不超过200K;</div>
									</div>
								</div>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</a-tab-pane>
		</a-tabs>

		<!-- <PcConfig v-if="configKey == '1'" />
		<AppConfig v-if="configKey == '2'" /> -->
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="imageUrl" />
		</a-modal>
	</div>
	<AnnexFormNew v-if="datas" :isup="false" ref="annex" type="APP" />
	<div class="uiue-card btn" :class="{ btnposi: activeIndex == 2 || activeIndex == 3 }">
		<a-button class="bt1" :loading="btnloding" @click="backs">取消</a-button>
		<a-button type="primary" :loading="btnloding" @click="submit">提交审批</a-button>
	</div>
	<PickPeople ref="pick" @succses="setUser" v-if="roleList.length > 0" :roleList="roleList" />
</template>

<script setup name="Mobile">
import LabelDes from './LabelDes.vue'
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import fileApi from '@/api/dev/fileApi'
import appInfoApi from '@/api/biz/appInfoApi'
import bizRoleApi from '@/api/biz/bizRoleApi'
import AnnexFormNew from './form/annexFormNew.vue'
import tool from '@/utils/tool'
import roleApi from '@/api/sys/roleApi'
import { cloneDeep } from 'lodash-es'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import sysConfig from '@/config/index'
import PickPeople from '@/components/pickPeople/index.vue'
import store from '@/store'
const route = useRoute()
const router = useRouter()
const configKey = ref('1')
const pickss = ref(null)
const pick = ref(null)
const annex = ref(null)
const formRef = ref(null)
const btnloding = ref(false)
const wsyy =
	'根据集团管理要求，为保证移动办公体验，需应用进行双端待办待阅同步接入，如无法双端同步，需填写原因并进行归口业务管理部门审核'
const contentStyle = {
	maxHeight: '64px',
	overflowY: 'auto'
}
// 默认要校验的
onMounted(() => {
	detailDate()
})
//路由返回
const backs = () => {
	store.commit('removeViewTags', route)
	router.back()
}
const fitForm = () => {
	submitForm.value.editAppType = '2'
	submitForm.value.appId = datas.value.appId
	submitForm.value.appInfoAppPropertiesAddParam.id = datas.value.appInfoAppPropertiesAddParam.id
	submitForm.value.appInfoAppPropertiesAddParam = Object.fromEntries(
		Object.entries(submitForm.value.appInfoAppPropertiesAddParam).map(([key, value]) => [key, value ? typeof value === 'string' ? value.trim() : value : value])
	);
}
const mobileOk = async () => {
	btnloding.value = true
	try {
		fitForm()
		await appInfoApi.appAccesssTest(submitForm.value)
		btnloding.value = false
		backs()
	} catch (error) {
		console.log(error)
		btnloding.value = false
	}
}

// 获取选人组件的角色
let roleList = ref([])
const getRoleList = async (params) => {
	const query = await appInfoApi.getFlowNew(params)
	// 通过变更出现的移动端接入
	if (query?.flow === 'test') {
		mobileOk()
		return false
	}



	const obj = {
		roleId: query.flow,
		searchKey: '2',
		ascriptionId: datas.value.platformBelongId,
		appId: datas.value.appId
	}
	roleList.value = await bizRoleApi.getList(obj)
	if (roleList.value.length == 0) {
		Modal.confirm({
			title: '提示',
			icon: createVNode(ExclamationCircleOutlined),
			content: '当前环节无可选人员，请联系双门户管理员hqs-swxreq@chinaunicom.cn',
			okText: '确认',
			cancelText: '取消',
		});
	}
	pick.value.setVisible(true)
}
const appInfoApiList = async () => {
	let arr = await roleApi.getPermissionsdl()
	let hqArr = arr.filter((v) => v.deptId === '001000')
	let allArr = arr.filter((v) => v.deptId !== '001000')
	allArr.sort((a, b) => a.deptId - b.deptId)
	const unicoms = sysConfig.UNICOM_APPRANG
	const list = [...unicoms, ...hqArr, ...allArr]
	platform.value = list.find((v) => v.deptId === datas.value.platformBelongId).orgName
}
// 应用联系人数据过滤显示
const appContact = ref()
const isPM = () => {
	appInfoApi.isPM().then((data) => {
		let obj = data.find((v) => v.id == datas.value.appContact)
		appContact.value = `${obj?.name || ''} ${obj?.phone || ''} ${obj?.email || ''}`
		// 如果是修改 获取显示的应用联系人
	})
}
const datas = ref()
const pcConfig = ref()
const showPermis = ref(false)
// const dyshow = ref(false)
const detailDate = async () => {
	datas.value = await appInfoApi.appInfoDetail({ appId: route.query.appId, type: '1' })

	appInfoApiList()
	isPM()
	if (datas.value.appAccess == 2) {
		showPermis.value = true
		formData.value.appSource = '2'
	} else {
		showPermis.value = false
		formData.value.appSource = '1'
	}
}
provide('editDate', datas)


const fileUrl = import.meta.env.VITE_FILE_URL
const pcLogo = computed(() => {
	let str = ''
	if (pcConfig.value.pcLogo.includes('group')) {
		str = `${sysConfig.FULL_URL}${pcConfig.value.pcLogo}`
	} else {
		str = `${fileUrl}/${JSON.parse(pcConfig.value.pcLogo)[0].url}`
	}
	return str
})

const fileImgType = '.jpg,.png,.jpeg,'

const customRequest = (file) => {
	// 后端需要接受的参数是 formData数据，
	const form = new FormData()
	form.append('file', file.file)
	fileApi
		.uploadCosReturnUrlPub(form)
		.then((res) => {
			let arr = [{ name: file.file.name, url: res }]
			formData.value.appLogo = JSON.stringify(arr)
			file.onSuccess(res, file.file)
			file.status = 'done'
		})
		.catch((err) => {
			setTimeout(() => {
				file.onError()
			}, 1000)
		})
}

const getBase64 = (img, callback) => {
	const reader = new FileReader()
	reader.addEventListener('load', () => callback(reader.result))
	reader.readAsDataURL(img)
}
const isClear = ref(true)
const handleChange = (info) => {
	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}
	if (info.file.status === 'done') {
		// Get this url from response in real world.
		getBase64(info.file.originFileObj, (base64Url) => {
			imageUrl.value = base64Url
			loading.value = false
		})
	}
	if (info.file.status === 'error') {
		loading.value = false
		fileList.value = []
		// message.error('upload error')
	}
	if (info.file.status === 'removed') {
		formData.value.appLogo = ''
	}
	if (!isClear.value) {
		fileList.value = []
		formData.value.appLogo = ''
		isClear.value = true
	}
}
const beforeUpload = (file) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
	if (!isJpgOrPng) {
		message.error('图片类型不对')
	}
	const isLt2K = file.size / 1024 < 200
	if (!isLt2K) {
		message.error('图片大小不超过200K')
	}
	isClear.value = isJpgOrPng && isLt2K
	return isJpgOrPng && isLt2K
}

const mobile = ref()
// 表单数据
const formData = ref({
	appSource: '1',
	isHideLogo: '1'
})

// 环境 https://生产  http://测试
const circum = computed(() => {
	return sysConfig.NODE_ENV === 'production' ? 'https://' : 'http://'
})


const validatePass = async (_, value) => {
	const reg = /^([1-9]\d|[1-9])(\.([0-9]){1,3}){1,9}$/
	if (!value) {
		return Promise.reject('请输入版本号')
	}
	if (!reg.test(value)) {
		return Promise.reject('请输入正确的版本号')
	}
	return Promise.resolve()
}
const valiUrl = async (_, value) => {
	if (!value) {
		return Promise.reject('请输入应用访问URL地址')
	}
	if (/[\u4E00-\u9FA5]/g.test(value)) {
		return Promise.reject('不能输入汉字!')
	}
	return Promise.resolve()
}
// 默认要校验的
const formRules = {
	appSource: [{ required: true, message: '请选择应用来源', trigger: 'blur' }],
	appVersion: [{ required: true, validator: validatePass, tirgger: 'blur' }],
	appVersionNote: [{ required: true, message: '请输入版本说明', trigger: 'blur' }],
	appUrl: [{ required: true, validator: valiUrl, tirgger: 'blur' }],
	appOnlineTime: [{ required: true, message: '请选择时间', trigger: 'blur' }],
	isHideLogo: [{ required: true, message: '请选择', trigger: 'blur' }],
	appLogo: [{ required: true, message: '请选择logo', trigger: 'blur' }],
	permission: [{ required: true, message: '请选择权限名单', trigger: 'blur' }]

}

const fileList = ref([])
const loading = ref(false)

const platform = ref()
// const config = [
// 	{ txt: '门户Html', key: '1', type: 'pcPropertiesList', oid: 'PC' },
// 	{ txt: '移动端Html', key: '2', type: 'appPropertiesList', oid: 'APP' },
// 	{ txt: 'Android', key: '3', type: 'androidPropertiesList', oid: 'ANDROID' },
// 	{ txt: 'IOS', key: '4', type: 'iosPropertiesList', oid: 'IOS' },
// 	{ txt: '移动端UMAP', key: '5', type: 'umapPropertiesList', oid: 'UMAP' }
// ]
const config = sysConfig.DEVICE_CONFIG
const appAccess = computed(() => {
	let str = ''
	let arr = config.filter((v) => '1,2'.includes(v.key))
	str = arr.map((v) => v.txt).join()
	return str
})

// 单选option
const radioOption = [
	{ label: '是', value: '1' },
	{ label: '否', value: '0' }
]
// 单选option
const radioOption11 = [
	{ label: '全国', value: '0' },
	{ label: '白名单', value: '1' }
]
// 单选数据过滤
const filterRadio = (val) => {
	if (val) {
		const obj = radioOption.find((item) => item.value == val)
		return obj.label
	}
}

const imageUrl = ref('')
let previewVisible = ref(false)
const handlePreview = (url) => {
	imageUrl.value = url
	previewVisible.value = true
}
const handleCancel = () => {
	previewVisible.value = false
}

const handleValidate = () => {
	return new Promise((resolve, reject) => {
		formRef.value
			.validate()
			.then(() => {
				resolve(true)
			})
			.catch(() => {
				console.log('失败')
				resolve(false)
			})
	})
}
const mobileValidate = () => {
	return new Promise((resolve, reject) => {
		mobile.value
			.validate()
			.then(() => {
				resolve(true)
			})
			.catch(() => {
				console.log('失败')
				resolve(false)
			})
	})
}
// 给h5参数信息赋值
const setParam = () => {
	const obj1 = {}
	let arr = []
	obj1[datas.value.appName] = {
		appid: 'xxxxx',
		appname: datas.value.appName,
		id: 'xxxxx',
		params: {
			app_name: '',
			app_type: '', // db || yb || dy || yy
			tag_type: '',
			encode_url: '',
			title: '',
			url: ''
		},
		subsystem: '其他',
		system: datas.value.appName,
		tagtype: '其他'
	}

	if (datas.value.isAppTodo === '1') {
		// 接入待办
		let appType = ['db', 'yb']
		appType.forEach((v) => {
			let obj = cloneDeep(obj1)
			obj[datas.value.appName].params.app_type = v
			arr.push(obj)
		})
	}
	if (datas.value.isAppReadtodo === '1') {
		// 接入待阅
		let appType = ['dy', 'yy']
		appType.forEach((v) => {
			let obj = cloneDeep(obj1)
			obj[datas.value.appName].params.app_type = v
			arr.push(obj)
		})
	}

	submitForm.value.appInfoAppPropertiesAddParam.param = arr.length > 0 ? JSON.stringify({ ...arr }) : ''
}
const submitForm = ref({})


const lastClickTime = ref(0)
const clickInterval = ref(1000) // 定义点击间隔为1秒
const submit = async () => {

	const currentTime = Date.now();
	if (currentTime - lastClickTime.value < clickInterval.value) {
		// 时间间隔过小，直接返回
		return;
	}
	lastClickTime.value = currentTime;


	const mobile = await mobileValidate()
	if (!mobile) {
		message.warning('请完善移动端HTML配置信息')
		return false
	}
	// 调用子组件annex的校验方法并返回子组件的formData
	// const annexVali = await annex.value.handleValidate()
	// if (!annexVali) {
	// 	message.warning('请完善附件信息')
	// 	return false
	// }
	const annexVali = annex.value.retForm()
	submitForm.value.appInfoAppPropertiesAddParam = cloneDeep({ ...formData.value, ...annexVali })
	setParam()
	const obj = cloneDeep(datas.value)
	const flowParams = {
		isPcTodo: obj.isPcTodo,
		isPcReadtodo: obj.isPcReadtodo,
		isAppTodo: obj.isAppTodo,
		isAppReadtodo: obj.isAppReadtodo,
		appRange: obj.appRange,
		type: '4'    // 0 新建应用 4 接入
	}
	// obj.appAccess = obj.appAccess.join(',')
	getRoleList(flowParams)


}

// 提交表单
const onOK = () => {
	fitForm()
	// console.log(submitForm.value)
	// return
	btnloding.value = true
	appInfoApi.appAccesss(submitForm.value).then((res) => {
		btnloding.value = false
		backs()
	}).catch(() => {
		btnloding.value = false
	})
}
// 人员选择完成
const setUser = (user) => {
	if (user && user.length > 0) {
		submitForm.value.approvalUsers = user
		pick.value.setVisible(false)
		onOK()
	}
}
</script>

<style lang="less" scoped>
.descri {
	margin-top: 10px;
}

.form-box {


	&-inp {
		border-radius: 4px;
		border: 1px solid rgb(206, 206, 206);
	}
}

.img-sty {
	width: 104px;
	height: 104px;
	cursor: pointer;
}

.btn {
	text-align: right;

	.bt1 {
		margin-right: 10px;
	}
}
</style>
<style>
/* .scro .ant-descriptions-item-container .ant-descriptions-item-content {
	color: red !important;
} */

.scro .ant-descriptions-item-content::-webkit-scrollbar {
	width: 6px;
	height: 10px;
}

.scro .ant-descriptions-item-content::-webkit-scrollbar-track {
	width: 4px;
	background: rgba(#101F1C, 0.1);
	-webkit-border-radius: 2em;
	-moz-border-radius: 2em;
	border-radius: 2em;
}

.scro .ant-descriptions-item-content::-webkit-scrollbar-thumb {
	background-color: rgba(144, 147, 153, .5);
	background-clip: padding-box;
	min-height: 28px;
	-webkit-border-radius: 2em;
	-moz-border-radius: 2em;
	border-radius: 2em;
	transition: background-color .3s;
	cursor: pointer;
}

.scro .ant-descriptions-item-content::-webkit-scrollbar-thumb:hover {
	background-color: rgba(144, 147, 153, .3);
}
</style>
